package pe.com.itworth.ttsclient.controller;

import java.util.Collection;
import java.util.Locale;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

import pe.com.itworth.ttsclient.infrastructure.MailManager;
import pe.com.itworth.ttsclient.infrastructure.MailMannagerGMAILImpl;
import pe.com.itworth.ttsclient.infrastructure.MailReaderJavaMailImpl;
import pe.com.itworth.ttsclient.infrastructure.Parser;
import pe.com.itworth.ttsclient.infrastructure.ParserGSON;
import pe.com.itworth.ttsclient.shared.AccountInfoDTO;
import pe.com.itworth.ttsclient.shared.FolderInfoDTO;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.TabHost;

public class MailboxTabPanelController extends TabActivity implements
		TextToSpeech.OnInitListener {

	protected static final String TAG = "TTS";
	public static TextToSpeech tts;
	
	private MailManager mailManager;
	
	private Collection<FolderInfoDTO> folders;
	
	private AccountInfoDTO accountInfoDTO;
	
	public void onCreate(Bundle b) {

		super.onCreate(b);
		setContentView(R.layout.mailboxtabpanel);

		// Initialize text-to-speech. This is an asynchronous operation.
		// The OnInitListener (second argument) is called after initialization
		// completes.
		tts = new TextToSpeech(this, this // TextToSpeech.OnInitListener
		);
		
		Bundle bu = getIntent().getExtras();
		if (bu != null) {
			Parser parser = new ParserGSON();
			accountInfoDTO = (AccountInfoDTO) parser.aObjeto(bu.getString("account"),
					AccountInfoDTO.class);
		}
		
		Runnable retrievingDataRunnable = new Runnable() {
			@Override
			public void run() {
				vDownloadFolders();
			}
		};

		Thread thread = new Thread(null, retrievingDataRunnable, "MagentoBackground");
		thread.start();

	}

	@Override
	public void onDestroy() {
		// Don't forget to shutdown!
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}

		super.onDestroy();
	}

	// Implements TextToSpeech.OnInitListener.
	public void onInit(int iStatus) {
		// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
		if (iStatus == TextToSpeech.SUCCESS) {
			// Set preferred language to US english.
			// Note that a language may not be available, and the result will
			// indicate this.
			int result = tts.setLanguage(new Locale("es", "ES"));
			// Try this someday for some interesting results.
			// int result mTts.setLanguage(Locale.FRANCE);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				// Lanuage data is missing or the language is not supported.
				Log.e(TAG, "Language is not available.");
			} else {
				// Check the documentation for other possible result codes.
				// For example, the language may be available for the locale,
				// but not for the specified country and variant.

				// The TTS engine has been successfully initialized.
				// Allow the user to press the button for the app to speak
				// again.
				// mAgainButton.setEnabled(true);
				// Greet the user.
				// sayHello();
			}
		} else {
			// Initialization failed.
			Log.e(TAG, "Could not initialize TextToSpeech.");
		}
	}

	private void vDownloadFolders() {

		mailManager = new MailMannagerGMAILImpl(accountInfoDTO, new MailReaderJavaMailImpl());

		try {
			folders = mailManager.getFolderNames();

			Integer iNumberOfMails = 0;
			if (folders != null)
				iNumberOfMails = folders.size();

		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
//		Log.i("ARRAY", "" + folders.size());

		runOnUiThread(populateMailListAndDismissRunnable);
	}
	
	
	private Runnable populateMailListAndDismissRunnable = new Runnable() {
		@Override
		public void run() {
			
			Resources res = getResources(); // Resource object to get Drawables
			TabHost tabHost = getTabHost(); // The activity TabHost
			TabHost.TabSpec spec; // Resusable TabSpec for each tab
			
			Parser parser = new ParserGSON();
			
			for (FolderInfoDTO folder : folders) {
				Intent newIntent = newIntent(MailboxController.class);
				Bundle bundle = new Bundle();
				bundle.putString("folder", parser.aCadena(folder));
				bundle.putString("account", parser.aCadena(accountInfoDTO));
				newIntent.putExtras(bundle);
				
				spec = tabHost
						.newTabSpec(folder.getsName())
						.setIndicator(folder.getsName(),
								res.getDrawable(R.drawable.icono_incognita))
						.setContent(newIntent);
				tabHost.addTab(spec);
			}
			
			tabHost.setCurrentTab(0);
		}
	};
	
	private Intent newIntent(Class activityClass) {
		return new Intent(this, activityClass);
	}

}
